<template>
	<view>
		<view style="background-color: #FFFFFF;">
			<cu-custom :isBack="true">
				<block slot="backText"></block>
				<block slot="content">{{corpCode}}-条码比对</block>
			</cu-custom>
		</view>
		<view class="cu-bar bg-white search fixed indexes" :style="[{top:CustomBar + 'px'}]">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input @confirm="getData" v-model="inputVal" type="text" placeholder="输入关键词" :focus="focus"></input>
			</view>
			<view class="action" @click="toScan">
				<text class="cuIcon-scan" style="font-size: 56rpx;"></text>
			</view>
		</view>
		<view class="cu-bar bg-white solid-bottom margin-top " style="margin-top: 13%;">
			<view class="action text-xl">
				<text class="cuIcon-title text-orange"></text>是否核对包裹码
			</view>
			<view class="margin-right">
				<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
			</view>
		</view>
		<scroll-view scroll-y="true" class="indexes" :scroll-with-animation="true" :enable-back-to-top="true"
			:style="[{height:'calc(100vh - '+ CustomBar + 'px - 100px)'}]">
			<view class="bg-white margin-bottom">
				<view>
					<view class="flex-sub text-center solid-bottom text-md padding">
						<text class="text-black text-bold">SRM结果</text>
						<text v-if="isMultiScanMode" class="text-gray text-sm margin-left-xs">
							(扫描1次)
						</text>
					</view>
				</view>
				<view class="text-gray cu-form-group">
					<text class="text-blue margin-right-xs">编码：{{srmviewCode}}</text>
				</view>
			</view>
			<view v-if="isShowe" class="action-section">
				<image src="../../static/dh.png" mode="aspectFit" style="width: 50px;height: 50px;"></image>
			</view>
			<view v-if="isShowo" class="action-section">
				<image src="../../static/cw.png" mode="aspectFit" style="width: 50px;height: 50px;"></image>
			</view>
			<view class="bg-white margin-bottom">
				<view>
					<view class="flex-sub text-center solid-bottom text-md padding ">
						<text class="text-black text-bold">海外仓结果</text>
						<text v-if="isMultiScanMode" class="text-gray text-sm margin-left-xs">
							(扫描{{hwRequiredScanCount}}次)
						</text>
					</view>
				</view>
				<view class="text-gray cu-form-group">
					<text class="text-blue margin-right-xs">编码：{{hwcode}}</text>
				</view>
				<!-- 显示扫描进度 -->
				<view v-if="isMultiScanMode && hwcodeScanCount > 0" class="text-gray cu-form-group">
					<text class="text-orange margin-right-xs">
						海外仓扫描进度：{{hwcodeScanCount}}/{{hwRequiredScanCount}}
					</text>
				</view>
				<!-- 显示总扫描进度 -->
				<!-- <view v-if="switchA && frequency > 1 && totalScanCount > 0" class="text-gray cu-form-group">
					<text class="text-green margin-right-xs">
						总扫描进度：{{totalScanCount}}/{{frequency}}
					</text>
				</view> -->
				<!-- 显示已扫描的编码列表 -->
				<view v-if="isMultiScanMode && hwcodeScanList.length > 0" class="text-gray cu-form-group flex justify-start">
					<text class="text-gray text-sm">海外仓扫描编码：</text>
					<view>
						<view v-for="(code, index) in hwcodeScanList" :key="index" class="margin-top-xs">
							<text class="text-blue text-sm">第{{index + 1}}次：{{code}}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				focus: true,
				menuArrow: true,
				CustomBar: this.CustomBar, //滚动定位用
				inputVal: "", //扫码值
				cdata: '', //任务列表
				hwcode: '', //海外仓存货编码
				hwname: '', //海外仓存货名称
				srmviewCode: '', //srm存货编码
				srmcinvname: '', //srm存货名称
				posList: [],
				// isCheck: false, //是否可用
				isShowe: false,
				isShowo: false,
				vals: '',
				markCode: '', //装code变量
				supplierId:'',//供应商Id
				switchA: true,
				frequency: 1,
				// 新增的海外仓多次扫描相关变量
				hwcodeScanList: [], // 海外仓扫描结果列表
				hwcodeScanCount: 0, // 海外仓当前扫描次数
				srmScanCount: 0, // SRM扫描次数
				totalScanCount: 0, // 总扫描次数
				srmCodePattern: '', // SRM码的格式模式
				hwCodePattern: '', // 海外仓码的格式模式
				hasConfirmedSrmPattern: false, // 是否已确认SRM码格式
				hasConfirmedHwPattern: false, // 是否已确认海外仓码格式
				isSubmiting: false, // 是否提交
			}
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'auditlist', 'corpCode']),
			// 检查frequency是否有效
			isFrequencyValid() {
				return this.frequency !== '' && this.frequency !== 0 && this.frequency !== '0' && this.frequency > 0;
			},
			// 是否启用多次扫描模式
			isMultiScanMode() {
				return this.switchA && this.isFrequencyValid && this.frequency > 1;
			},
			// 海外仓需要扫描的次数 = frequency - SRM扫描次数(1次)
			hwRequiredScanCount() {
				// 如果frequency无效或switchA为false，海外仓只扫描1次
				if (!this.isMultiScanMode) {
					return 1;
				}
				return Math.max(this.frequency - 1, 1);
			},
			// 总的需要扫描次数
			totalRequiredScanCount() {
				// 如果frequency无效或switchA为false，总共扫描2次（SRM1次+海外仓1次）
				if (!this.isMultiScanMode) {
					return 2;
				}
				return this.frequency;
			}
		},
		onShow() {

		},
		onLoad(params) {
			this.markCode = JSON.parse(params.data).code
			this.supplierId = JSON.parse(params.data).supplierId || ''
			this.frequency = JSON.parse(params.data).frequency || ''

			// 如果frequency为''或者为0，默认switchA为false
			if (this.frequency === '' || this.frequency === 0 || this.frequency === '0') {
				this.switchA = false;
			}
		},
		methods: {
			SwitchA(e) {
				this.switchA = e.detail.value
				// 当开关状态改变时，重置所有扫描状态
				this.resetAllScan();
				
			},
			/** 获取数据 扫描盘点任务单，获取当前盘点人需盘点货位列表*/
			getData() {
				this.cdata = '';
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.focus = true; //  第二个输入框获取焦点
				}, 500)

				// 优化后的扫描逻辑
				this.processScannedCode(this.inputVal);
			},

			/** 处理扫描的码 - 核心优化逻辑 */
			processScannedCode(scannedCode) {
				// 1. 检查是否可以通过本地格式判断
				const localJudgment = this.getLocalCodeType(scannedCode);

				if (localJudgment !== null) {
					// 可以本地判断，直接处理
					this.handleCodeByLocalJudgment(scannedCode, localJudgment);
				} else {
					// 需要调用checkBarCode接口
					this.callCheckBarCodeAPI(scannedCode);
				}
			},

			/** 本地格式判断 */
			getLocalCodeType(scannedCode) {
				// 如果已经确认了SRM码格式，检查是否匹配
				if (this.hasConfirmedSrmPattern && this.srmCodePattern) {
					if (this.matchesPattern(scannedCode, this.srmCodePattern)) {
						return 'srm';
					}
				}

				// 如果已经确认了海外仓码格式，检查是否匹配
				if (this.hasConfirmedHwPattern && this.hwCodePattern) {
					if (this.matchesPattern(scannedCode, this.hwCodePattern)) {
						return 'hw';
					}
				}

				// 无法本地判断，需要调用接口
				return null;
			},

			/** 检查码是否匹配已知模式 */
			matchesPattern(code, pattern) {
				// 简单的模式匹配：检查前缀、长度等
				// 这里可以根据实际业务规则来优化
				if (pattern.prefix && !code.startsWith(pattern.prefix)) {
					return false;
				}
				if (pattern.length && code.length !== pattern.length) {
					return false;
				}
				return true;
			},

			/** 根据本地判断结果处理码 */
			handleCodeByLocalJudgment(scannedCode, codeType) {
				setTimeout(()=>{
					this.inputVal = '';
				},50)

				if (codeType === 'srm') {
					// 检查是否重复扫描SRM码
					if (this.srmviewCode === scannedCode) {
						// 连续扫描一样的SRM码，不做处理
						return;
					}
					this.handleSrmCodeScan(scannedCode, false);
				} else if (codeType === 'hw') {
					// 海外仓码，检查一致性
					if (this.hwcodeScanList.length > 0) {
						const isConsistent = this.hwcodeScanList.every(code => code === scannedCode);
						if (!isConsistent) {
							// 不一致，立即报错
							this.$api.msg(`海外仓扫描结果不一致`);
							this.playMismatchSound();
							this.resetHwScan();
							return;
						}
					}
					this.handleHwCodeScan(scannedCode, false);
				}
			},

			/** 调用checkBarCode接口 */
			callCheckBarCodeAPI(scannedCode) {
				// 防抖检查：如果API正在调用中，则不允许再次调用
				if(!scannedCode) {
					return
				}
				if (this.isSubmiting) {
					// console.log('API调用中，请等待完成后再试');
					this.$api.msg('API调用中，稍后再试');
					return;
				}

				try {
					this.isSubmiting = true;
					uni.request({
						url: this.serverURL_a + `/barcode/decode/checkBarCode`,
						data: {
							barCode: scannedCode,
							__sid: this.userInfo.sessionid,
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						},
						method: 'POST',
						success: function(data) {
							let res = data.data
							if(res.result == 'true'){
								// SRM码 - 记录格式模式
								this.recordSrmPattern(scannedCode);
								this.handleSrmCodeScan(scannedCode, true);
							}else if(res.result == 'false') {
								// 海外仓码 - 记录格式模式
								this.recordHwPattern(scannedCode);
								// 如果已有海外仓码，检查一致性
								if (this.hwcodeScanList.length > 0) {
									const isConsistent = this.hwcodeScanList.every(code => code === scannedCode);
									if (!isConsistent) {
										this.$api.msg(`海外仓扫描结果不一致`);
										this.playMismatchSound();
										this.resetHwScan();
										return;
									}
								}
								this.handleHwCodeScan(scannedCode, true);
							} else {
								this.$api.msg(`扫描结果未知`);
								this.playMismatchSound();
								this.resetHwScan();
								return;
							}
						}.bind(this),
						fail: function() {
							this.$api.msg('无法连接服务，请联系管理');
							this.inputVal = ''
							return;
						}.bind(this),
						complete: function() {
							// 无论成功或失败，最终都要重置API调用状态
							this.isSubmiting = false;
						}.bind(this)
					})
				} catch (error) {
					console.error('调用checkBarCode接口时出错:', error);
					this.$api.msg('调用接口失败，请联系管理');
					return;
				} finally {
					// 无论是否成功，都将提交状态重置为false
					this.isSubmiting = false
				} 
			},

			/** 记录SRM码格式模式 */
			recordSrmPattern(srmCode) {
				if (!this.hasConfirmedSrmPattern) {
					this.srmCodePattern = this.extractPattern(srmCode);
					this.hasConfirmedSrmPattern = true;
				}
			},

			/** 记录海外仓码格式模式 */
			recordHwPattern(hwCode) {
				if (!this.hasConfirmedHwPattern) {
					this.hwCodePattern = this.extractPattern(hwCode);
					this.hasConfirmedHwPattern = true;
				}
			},

			/** 提取码的格式模式 */
			extractPattern(code) {
				// 提取前缀（前3个字符）和长度
				return {
					prefix: code.substring(0, Math.min(3, code.length)),
					length: code.length
				};
			},



			/** 处理SRM码扫描 */
			handleSrmCodeScan(scannedCode) {
				this.srmviewCode = scannedCode;
				this.srmScanCount = 1;
				this.totalScanCount = this.srmScanCount + this.hwcodeScanCount;

				setTimeout(()=>{
					this.inputVal = '';
				},50)

				if (!this.switchA) {
					// switchA为false时，保持原来的逻辑
					this.checkAndSubmit();
					return;
				}

				// switchA为true时，检查是否可以提交
				this.checkAndSubmit();
			},

			/** 处理海外仓码扫描 */
			handleHwCodeScan(scannedCode) {
				if (!this.switchA) {
					// switchA为false时，保持原来的逻辑
					this.hwcode = scannedCode;
					this.hwcodeScanCount = 1;
					setTimeout(()=>{
						this.inputVal = '';
					},50)
					this.checkAndSubmit();
					return;
				}

				// 确保hwcodeScanCount不会超过hwRequiredScanCount
				if (this.hwcodeScanCount >= this.hwRequiredScanCount) {
					this.$api.msg(`扫其他码`);
					setTimeout(()=>{
						this.inputVal = '';
					},50)
					return;
				}


				// switchA为true时，需要多次扫描
				this.hwcodeScanCount++;
				this.hwcodeScanList.push(scannedCode);
				this.totalScanCount = this.srmScanCount + this.hwcodeScanCount;

				setTimeout(()=>{
					this.inputVal = '';
				},50)

				if (this.hwcodeScanCount < this.hwRequiredScanCount) {
					// 还需要继续扫描海外仓码
					const remaining = this.hwRequiredScanCount - this.hwcodeScanCount;
					this.$api.msg(`海外仓还需扫描${remaining}次`);
					return;
				}

				// 海外仓扫描次数已达到要求，所有结果一致，直接完成
				this.hwcode = scannedCode;
				this.$api.msg(`${this.hwRequiredScanCount}次海外仓扫描完成`);
				this.checkAndSubmit();
			},

			/** 播放不匹配音效 */
			playMismatchSound() {
				console.log("=====播放不匹配音效=====");
				let src = '../../static/bpp.mp3'; // 使用扫码失败的音效
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src;
				Audio.play();
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('不匹配音效播放结束');
					Audio.destroy();
				});
			},

			/** 检查并提交数据 */
			checkAndSubmit() {
				if (!this.switchA) {
					// switchA为false时，需要SRM和海外仓都有值才能提交
					if (this.srmviewCode && this.hwcode) {
						this.getPostData();
					}
					return;
				}

				// switchA为true时，检查是否达到总扫描次数要求
				if (this.totalScanCount >= this.frequency && this.srmviewCode && this.hwcode) {
					this.getPostData();
				}
			},

			/** 重置海外仓扫描状态 */
			resetHwScan() {
				this.hwcodeScanList = [];
				this.hwcodeScanCount = 0;
				this.hwcode = '';
				this.totalScanCount = this.srmScanCount + this.hwcodeScanCount;
				setTimeout(()=>{
					this.inputVal = '';
				},50)
			},

			/** 重置所有扫描状态 */
			resetAllScan() {
				this.srmviewCode = '';
				this.srmScanCount = 0;
				this.srmCodePattern = '';
				this.hwCodePattern = '';
				this.hasConfirmedSrmPattern = false;
				this.hasConfirmedHwPattern = false;
				this.resetHwScan();
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.focus = true; //  第二个输入框获取焦点
				}, 500)
			},

			/** 标准标签信息*/
			getPostData() {
				setTimeout(()=>{
					this.inputVal = '';
				},50)
				if (!this.srmviewCode || !this.hwcode) {
					this.$api.msg("请继续另一个码!");
					return;
				} else {
					uni.request({
						url: this.serverURL_a + '/so/App/checkSkuAndCode',
						data: {
							code: this.markCode,
							supplierId: this.supplierId,
							__sid: this.userInfo.sessionid,
							srmCode: this.srmviewCode,
							cusCode: this.hwcode,
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						},
						method: 'POST',
						success: function(res) {
							var result = res.data;
							if (result.result == 'true') {
								console.log("成功")
								//提示成功声
								console.log("=====testClick=====");
								let src = '../../static/cg1.mp3';
								//实例化声音  
								const Audio = uni.createInnerAudioContext();
								Audio.autoplay = true;
								Audio.src = src; //音频地址  
								Audio.play(); //执行播放  
								Audio.onError((res) => {
									console.log(res.errMsg);
									console.log(res.errCode);
								});
								Audio.onPause(function() {
									console.log('end');
									Audio.destroy();
								});
								setTimeout(()=>{
									this.inputVal = '';
								},50)
								this.cleanData();
							} else if (result.result == '1003') {
								console.log('end');
								this.$api.msg(result.message);
								console.log(result.message)
								console.log("SKU不存在！")
								console.log("=====testClick=====");
								let src = '../../static/bcz.mp3';
								//实例化声音  
								const Audio = uni.createInnerAudioContext();
								Audio.autoplay = true;
								Audio.src = src; //音频地址  
								Audio.play(); //执行播放  
								Audio.onError((res) => {
									console.log(res.errMsg);
									console.log(res.errCode);
								});
								Audio.onPause(function() {
									console.log('end');
									Audio.destroy();
								});
								setTimeout(()=>{
									this.inputVal = '';
								},50)
								this.cleanData();
								return;
							} else if (result.result == '1004') {
								this.$api.msg(result.message);
								console.log("请勿重复扫描！")
								console.log("=====testClick=====");
								let src = '../../static/chongfu.mp3';
								//实例化声音  
								const Audio = uni.createInnerAudioContext();
								Audio.autoplay = true;
								Audio.src = src; //音频地址  
								Audio.play(); //执行播放  
								Audio.onError((res) => {
									console.log(res.errMsg);
									console.log(res.errCode);
								});
								Audio.onPause(function() {
									console.log('end');
									Audio.destroy();
								});
								setTimeout(()=>{
									this.inputVal = '';
								},50)
								this.focus = true;
								this.cleanData();
								return;
							} else if (result.result == '1005') {
								this.$api.msg(result.message);
								console.log("数量超出！")
								console.log(result.message)
								console.log("=====testClick=====");
								let src = '../../static/slcc.mp3';
								//实例化声音  
								const Audio = uni.createInnerAudioContext();
								Audio.autoplay = true;
								Audio.src = src; //音频地址  
								Audio.play(); //执行播放  
								Audio.onError((res) => {
									console.log(res.errMsg);
									console.log(res.errCode);
								});
								Audio.onPause(function() {
									console.log('end');
									Audio.destroy();
								});
								setTimeout(()=>{
									this.inputVal = '';
								},50)
								setTimeout(() => {
									this.cleanData();
								}, 500)
								return;
							} else {
								this.$api.msg(result.message);
								console.log("扫码失败！")
								console.log(result.message)
								this.scSb();
								setTimeout(()=>{
									this.inputVal = '';
								},50)
								setTimeout(() => {
									this.cleanData();
								}, 500)
								return;
							}
						}.bind(this),
						fail: function() {
							this.$api.msg('服务已停止,请稍后再试');
							setTimeout(() => {
								this.inputVal = '';
								this.cleanData();
							}, 500)
							return;
						}.bind(this),
					});
				}
			},
			/** 扫码失败*/
			scSb() {
				console.log("=====testClick=====");
				let src = '../../static/smsb.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			/** 扫码成功*/
			scCg() {
				console.log("=====testClick=====");
				let src = '../../static/smcg.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			/** 清空数据 */
			cleanData() {
				this.focus = true;
				// 清空所有扫描相关数据
				this.resetAllScan();
			},
			/** 扫码*/
			toScan() {
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						var rdata = res.result;
						this.inputVal = rdata;
						setTimeout(function() {
							this.getData();
							this.inputVal = '';
							this.focus = true;
						}.bind(this), 100);
					}.bind(this)
				});
			},
		}
	}
</script>

<style lang="scss">
	.confirm-btn {
		padding: 0 38upx;
		margin: 0;
		height: 76upx;
		line-height: 76upx;
		font-size: $font-base + 2upx;
		background: $uni-color-primary;
	}

	.page {
		height: 100Vh;
		width: 100vw;
	}

	.page.show {
		overflow: hidden;
	}

	.switch-sex::after {
		content: "\e716";
	}

	.switch-sex::before {
		content: "\e7a9";
	}

	.switch-music::after {
		content: "\e66a";
	}

	.switch-music::before {
		content: "\e6db";
	}

	.indexes {
		font-size: 18px;
	}

	/* 底部栏 */
	.action-section {
		position: fixed;
		left: 85%;
		display: flex;
		/* align-items: center; */
	}
</style>